﻿var helper = new KssHelper();

var urlTag;
var upload;
var status;
var dg;
var score;
var cash;
jQuery(document).ready(function () {

    jQuery("#userselected input:checkbox").change(function () {
        jQuery("#userselected input:checkbox").attr("checked", false);
        jQuery(this).attr("checked", true);
    });
    jQuery("#A1selected input:checkbox").change(function () {
        jQuery("#A1selected input:checkbox").attr("checked", false);
        jQuery(this).attr("checked", true);
    });
    
    var widthmain = jQuery('.maincontent').width();
    jQuery('#documentTab').tabs({ 
        'width': widthmain,
        onSelect: function (title, index) {
            var node = jQuery('#tagTree').tree('find', 'tagAll');
            jQuery('#tagTree').tree('select', node);
            if (index == 0) {
                status = undefined;
            }
            if (index == 1) {
                status = 0;
            }
            else if (index == 2) {
                status = 10;
            }
            else if (index == 3) {
                status = 11;
            }
            else if (index == 4) {
                status = 20;
            }
            else if (index == 5) {
                status = 30;
            }
            else if (index == 6) {
                status = 40;
            }
            else if (index == 7) {
                if (currentRole != undefined && currentRole == "tqm") {
                    jQuery('#dgA1').datagrid({ url: "/api.ashx?metdhodName=getdocbyTqm" });
                    return false;
                }
            }
            else {
                if (jQuery('#dgA1')) {
                    jQuery('#dgA1').datagrid({
                        onDblClickRow: function (index, fields) {
                            A1ApproveDocument();
                        }
                    });
                }
            }
            if (status != undefined && status != 'undefined') {
                jQuery('#dg' + status).datagrid({
                    url: "/api.ashx?metdhodName=getdocbyUsername&UserName=" + currentUser + "&Status=" + status,
                    loadFilter: pagerFilter,
                    onDblClickRow: function (index, fields) {
                        editDocument(status, fields);
                    }
                });

            }
            else {
                jQuery('#dg').datagrid({
                    url: "/api.ashx?metdhodName=getdocbyUsername&UserName=" + currentUser,
                    loadFilter: pagerFilter,
                    onDblClickRow: function (index, fields, value) {
                        editDocument(undefined, fields);
                    }
                });
            }
            return false; // prevent from closing

        }
    });

    jQuery('#tagTree').tree({
        onClick: function (node) {
            if (status != undefined && status != 'undefined') {
                jQuery('#dg' + status).datagrid({ url: "/api.ashx?metdhodName=getdocbyUsername&UserName=" + currentUser + "&Status=" + status + "&Tag=" + node.id, loadFilter: pagerFilter });
            }
            else {
                jQuery('#dg').datagrid({ url: "/api.ashx?metdhodName=getdocbyUsername&UserName=" + currentUser + "&Tag=" + node.id, loadFilter: pagerFilter });
            }
            return false; // prevent from closing
        }
    });


    jQuery('#tagcate').combobox({
        onSelect: function (param) {
            var tagCageGet = tagsAll;
            var tag = '';
            tag = jQuery(jQuery.parseJSON(tagCageGet)).filter(function (index) {
                if (this.tagCateId != undefined && this.tagCateId != 'undefined') {
                    return this.tagCateId == param.value;
                }
            });
            jQuery('#tag').combobox('loadData', tag);
            jQuery('#tag').combobox({
                onSelect: function (param2) {
                    alert(param2.value);
                }
            });
        }
    });
    //getDocByID('doc1');
});
function formatStatus(val) {
    return helper.statusDisplay(val);
}
function SaveImage() {
    var row = jQuery('#dg').datagrid('getSelected');
    if (row != null || row != undefined) {
        return '/api.ashx?metdhodName=saveImage&id=' + row.id;
    }
    return '/api.ashx?metdhodName=saveImage';

}
function DeleteFile(file, id, propid) {
    jQuery('#UploadStatus').html("deleting...");
    jQuery.ajax({
        url: "/api.ashx?file=" + file + "&metdhodName=deleteImage&id=" + id + "&propid=" + propid,
        type: "GET",
        cache: false,
        async: true,
        success: function (html) {
            //jQuery('#UploadedFile').html("");
            jQuery("a[href='" + file + "']").next().remove();
            jQuery("a[href='" + file + "']").remove();
            jQuery('#UploadStatus').html("file has been deleted");
            jQuery("#UploadButton").show();

        }
    });

}
function pagerFilter(data) {
    if (typeof data.length == 'number' && typeof data.splice == 'function') {	// is array
        data = {
            total: data.length,
            rows: data
        }
    }
    var dg = jQuery(this);
    var opts = dg.datagrid('options');
    var pager = dg.datagrid('getPager');
    pager.pagination({
        onSelectPage: function (pageNum, pageSize) {
            opts.pageNumber = pageNum;
            opts.pageSize = pageSize;
            pager.pagination('refresh', {
                pageNumber: pageNum,
                pageSize: pageSize
            });
            dg.datagrid('loadData', data);
        }
    });
    if (!data.originalRows) {
        data.originalRows = (data.rows);
    }
    var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
    var end = start + parseInt(opts.pageSize);
    data.rows = (data.originalRows.slice(start, end));
    return data;
}
function getDocByID(id) {
    helper.GetDocByID(id, function (data) {
        jQuery('#kssForm').form('load', data[0]);

    });
}
function showPopup(divID) {

    jQuery('#' + divID).dialog('open');
}
function saveDocument(parameter){
    var row;
    if (status != undefined && status != 'undefined') {
        dg = '#dg' + status;
        row = jQuery(dg).datagrid('getSelected');
    }
    else {
        row = jQuery('#dg').datagrid('getSelected');
    }

    if (row != null || row != undefined) {
        parameter.push({ "propertyName": "id", "dataNvarchar": row.id });
    }

    if (row != null || row != undefined)
    {
        for (var i = 0; i < parameter.length; i++)
        {
            if (parameter[i].propertyname == "approver1")
            {
                if (parameter[i].dataNvarchar == row.approver1)
                {
                    parameter[i].dataNvarchar = "";
                }
            } else if (parameter[i].propertyname == "approver2")
            {
                if (parameter[i].dataNvarchar == row.approver2)
                {
                    parameter[i].dataNvarchar = "";
                }
            }
        }
    }

    var data2 = JSON.stringify(parameter);
    helper.InserForm(data2, function (result) {
        if (result.success) {
            jQuery('#dg').datagrid('reload'); // reload the user data
        } else {
            jQuery('#dg').datagrid('reload');
            jQuery.messager.show({	// show error message
                title: 'Error',
                msg: result.msg
            });
        }
        jQuery('#dlg').dialog('close')
    });
}

function getDocumentA1Data() {
    var approverType = jQuery('input:radio[name=approverTypeA1]:checked').val() //jQuery('#approver2Div input[name=approverType]:checked').val();
    if (approverType == '' || approverType == undefined) {
        jQuery.messager.alert('อนุมัติเอกสาร', 'กรุณาระบุการอนุมัติเอกสาร!');
        return false;
    }
    var param = getAllInput('form#fmA1 :input');
    var data1    = getAllInputApprover1();
    jQuery.each(param, function (i, d) {
        data1.push(d);
    });
    if (approverType == 1) {
        data1.push({ 'propertyName': 'score', 'dataInt': score });
        data1.push({ 'propertyName': 'cash', 'dataDecimal': cash });
        data1.push({ 'propertyName': 'status', 'dataInt': 10 });

    }
    else if (approverType == 2) {
        data1.push({ 'propertyName': 'cash', 'dataDecimal': 10 }); // give 10 bath
        data1.push({ 'propertyName': 'status', 'dataInt': 10 });
    }
    else {
        if (jQuery('#approver1Div #approver1Comment').val() != '') {
            data1.push({ 'propertyName': 'status', 'dataInt': 11 });
        }
        else {

            jQuery.messager.alert('ไม่อนุมัติแบบฟอร์ม', 'กรุณาระบุเหตุผลที่ไม่อนุมัติแบบฟอร์มด้วยค่ะ!');
            return false;
        }
    }
    data1.push({ 'propertyName': 'approved1Date', 'dataDate': new Date() });
    return data1;
}
function getDocumentA2Data() {
    var datas = [];
    var a1 = getDocumentA1Data();
    jQuery.each(a1, function (i, d) {
        if (d.propertyName != 'status') {
            datas.push(d);
        }
    });

    var approverType = jQuery('#approver2Div input[name=approverType]:checked').val(); // jQuery('input:radio[name=approvetype]:checked').val()
    if (approverType == '' || approverType == undefined) {
        jQuery.messager.alert('อนุมัติเอกสาร', 'กรุณาระบุการอนุมัติเอกสาร!');
        return false;
    }
    datas.push({ 'propertyName': 'approverType', 'dataNvarchar': approverType });
    datas.push({ 'propertyName': 'approver2Comment', 'dataNvarchar': jQuery('#approver2Div #approver2Comment').val() });
    if (approverType == '2') {
        if (jQuery('#approver2Div #approveWithBudget').val() == undefined || jQuery('#approver2Div #approveWithBudget').val() == '') {
            jQuery.messager.alert('อนุมัติและนำเสนอคณะกรรมการให้รับผลตอบแทน', 'กรุณาระบุจำนวนเงินที่ได้รับ!');
            return false;
        }
        else {
            datas.push({ 'propertyName': 'approveWithBudget', 'dataNvarchar': jQuery('#approver2Div #approveWithBudget').val() });
            datas.push({ 'propertyName': 'cash', 'dataDecimal': jQuery('#approver2Div #approveWithBudget').val() });
            datas.push({ 'propertyName': 'status', 'dataInt': 40 });
        }
    }
    else if (approverType == '3') {
        if (jQuery('#approver2Div #notapproveWithBudget').val() == undefined || jQuery('#approver2Div #notapproveWithBudget').val() == '') {
            jQuery.messager.alert('ไม่อนุมัติตามที่เสนอ แต่ให้รับผลตอบแทน', 'กรุณาระบุจำนวนเงินที่ได้รับ!');
            return false;
        }
        else if (jQuery('#approver2Div #approver2Comment').val() == undefined || jQuery('#approver2Div #approver2Comment').val() == '') {
            jQuery.messager.alert('ไม่อนุมัติแบบฟอร์ม', 'กรุณาระบุเหตุผลที่ไม่อนุมัติแบบฟอร์มด้วยค่ะ!');
            return false;
        }
        else {
            datas.push({ 'propertyName': 'notapproveWithBudget', 'dataNvarchar': jQuery('#approver2Div #notapproveWithBudget').val() });
            datas.push({ 'propertyName': 'cash', 'dataDecimal': jQuery('#approver2Div #notapproveWithBudget').val() });
            datas.push({ 'propertyName': 'status', 'dataInt': 40 });

        }
    }
    else {
        datas.push({ 'propertyName': 'status', 'dataInt': 40 });
    }
    datas.push({ 'propertyName': 'approved2Date', 'dataDate': new Date() });
    return datas;
}
function saveDocumentA1() {

    var data1 = getDocumentA1Data();
    if (data1 == false) {
        return false;
    }
    var row = jQuery('#dgA1').datagrid('getSelected');
    if (row != null || row != undefined) {
        data1.push({ "propertyName": "id", "dataNvarchar": row.id });
        var data2 = JSON.stringify(data1);
        helper.InserForm(data2, function (result) {
            if (result.success) {
                jQuery('#dgA1').datagrid('reload'); // reload the user data
            } else {
                jQuery('#dgA1').datagrid('reload');
                jQuery.messager.show({	// show error message
                    title: 'Error',
                    msg: result.msg
                });
            }
            //jQuery('#dlg').dialog('close')
        });
    }
    else {
        jQuery.messager.alert('ระบบขัดข้อง', 'ไม่สามารถแก้ไขเอกสารได้เนื่องจาก เลขที่เอกสารไม่ถูกต้อง!');
    }
    jQuery('#dlgA1').dialog('close')

}
function saveDocumentA2() {
    var datas = getDocumentA2Data();
    if (jQuery("approver1Div :input").attr("disabled") == undefined) {
        var a1 = getDocumentA1Data();
        if (a1 == false) {
            return false;
        }
        jQuery.each(a1, function (i, d) {
            if (d.propertyName != 'status') {
                datas.push(d);
            }
        });
    }
    
    if (datas == false) {
        return false;
    }
    var row = jQuery('#dgA1').datagrid('getSelected');
    if (row != null || row != undefined) {
        datas.push({ "propertyName": "id", "dataNvarchar": row.id });
        var data2 = JSON.stringify(datas);
        helper.InserForm(data2, function (result) {
            if (result.success) {
                jQuery('#dgA1').datagrid('reload'); // reload the user data
            } else {
                jQuery('#dgA1').datagrid('reload');
                jQuery.messager.show({	// show error message
                    title: 'Error',
                    msg: result.msg
                });
            }
        });
    }
    jQuery('#dlgA1').dialog('close');
}
function saveDocumentTQM() {
    var datas = [];
    if (jQuery("approver1Div :input").attr("disabled") == undefined) {
        var a1 = getDocumentA1Data();
        if (a1 == false) {
            return false;
        }
        jQuery.each(a1, function (i, d) {
            
            if (d.propertyName != 'status') {
                datas.push(d);
            }
        });
    }
    if (jQuery("#approver2Div :input").attr("disabled") == undefined) {
        var a2 = getDocumentA2Data();
        if (a2 == false) {
            return false;
        }
        jQuery.each(a2, function (i, d) {
            jQuery.each(datas, function (i2, d2) {
                if (d.propertyName == d2.propertyName) {
                    if (d.dataDecimal != undefined) {
                        d2.dataDecimal = d.dataDecimal;
                    }
                }
            });
            if (d.propertyName != 'status') {
                datas.push(d);
            }
        });
    }


    var approverTQMType = jQuery('#approverTQMDiv input[name=ApprovetypeTQM]:checked').val();
    if (approverTQMType == '' || approverTQMType == undefined) {
        jQuery.messager.alert('อนุมัติเอกสาร', 'กรุณาระบุการอนุมัติเอกสาร!');
        return false;
    }
    datas.push({ 'propertyName': 'approverTQMType', 'dataNvarchar': approverTQMType });
    if (approverTQMType == '2') {
        if (jQuery('#approverTQMDiv #approverTQMComment').val() == undefined || jQuery('#approverTQMDiv #approverTQMComment').val() == '') {
            jQuery.messager.alert('ไม่อนุมัติเอกสาร.', 'กรุณาระบุเหตุผลค่ะ!');
            return false;
        }
        else {
            datas.push({ 'propertyName': 'approverTQMComment', 'dataNvarchar': jQuery('#approverTQMDiv #approverTQMComment').val() });
            datas.push({ 'propertyName': 'status', 'dataInt': 11 });
        }
    }
    else {
        datas.push({ 'propertyName': 'status', 'dataInt': 30 });
        datas.push({ 'propertyName': 'approverTQMComment', 'dataNvarchar': jQuery('#approverTQMDiv #approverTQMComment').val() });
    }
    datas.push({ 'propertyName': 'approvedQMDate', 'dataDate': new Date() });

    var row = jQuery('#dgA1').datagrid('getSelected');
    if (row != null || row != undefined) {
        datas.push({ "propertyName": "id", "dataNvarchar": row.id });
        var tagCate = jQuery('#tagcate').combobox('getValues');
        var tagData = jQuery('#tag').combobox('getValues');
        var tagsData = [];
        if (tagData == undefined || tagData.length == 0) {
            jQuery.each(tagCate, function (i, cd) {
                tagsData.push({ 'docID': row.id, 'tagCateID': cd });
            });
        }
        else {
            jQuery.each(tagData, function (i, d) {
                tagsData.push({ 'docID': row.id, 'tagId': d, 'tagCateID': jQuery('#tagcate').combobox('getValue') });
            });
        }
        if (tagsData.length > 0) {
            datas.push({ "propertyName": "docTag", "dataNvarchar": JSON.stringify(tagsData) });
        }

        var data2 = JSON.stringify(datas);
        helper.InserForm(data2, function (result) {
            if (result.success) {
                jQuery('#dgA1').datagrid('reload'); // reload the user data
            } else {
                jQuery('#dgA1').datagrid('reload');
                jQuery.messager.show({	// show error message
                    title: 'Error',
                    msg: result.msg
                });
            }
        });
    }
    jQuery('#dlgA1').dialog('close');
}

function intiNewDocument() {
    if (currentUserFirstName == 'ผู้ทำเอกสารแทน') {
        jQuery('#createdByName').attr('readonly', false);
        jQuery('#createdBy').attr('readonly', false);
        jQuery('#departmentName').attr('readonly', false);
    }
    else {
        jQuery('#createdByName').val(currentUserFirstName);
        jQuery('#createdBy').val(currentUser);
    }
}

function newDocument() {

    UserCheckerFunction();
    jQuery("#userDiv").hide();
    jQuery("#Userapprover2Div").hide();
    jQuery("#UserapproverTQMDiv").hide();
    jQuery("form#fm :input").attr("disabled", false);
    jQuery("#UploadButton").show();
    jQuery('#dlg').dialog('open').dialog('setTitle', 'สร้างแบบฟอร์มใหม่');
    jQuery('#dg').datagrid('clearSelections');
    jQuery('#wizard').smartWizard('goToStep', 1);
    jQuery('#wizard').smartWizard('hideMessage');
    //jQuery.uniform.restore(jQuery('select, input:checkbox'));
    jQuery('#fm').form('clear');
    jQuery('#UploadedFile').html('');
    jQuery('#UploadedFileAfter').html('');
    //jQuery('select, input:checkbox').uniform();
    intiNewDocument();
    urlTag = '/api.ashx?metdhodName=addTag';

    upload = new AjaxUpload('#UploadButton', {
        action: SaveImage(),
        onComplete: function (file, response) {
            var obj = jQuery.parseJSON(response);
            jQuery("<a id='" + obj.propid + "' " + "class='preview imageuploaded' target='_blank' ' href='" + obj.imgPath + "'>" + file + " </a> <img src='/resources/btndelete.png' style='display:inline;' onclick=\"DeleteFile('" + obj.imgPath + "','','" + obj.propid + "')\"  class='delete'/>").appendTo('#UploadedFile');

            jQuery('#UploadStatus').html("file has been uploaded sucessfully");
            //jQuery("#UploadButton").hide();
            imagePreview();
        },
        onSubmit: function (file, ext) {
            if (!(ext && /^(txt|doc|docx|xls|xlsx|pdf|jpg)$/i.test(ext))) {
                alert('Invalid File Format.');
                return false;
            }
            jQuery('#UploadStatus').html("Uploading...");
        }
    });
    uploadAfter = new AjaxUpload('#UploadButtonAfter', {
        action: SaveImage(),
        onComplete: function (file, response) {
            var obj = jQuery.parseJSON(response);
            jQuery("<a id='" + obj.propid + "' " + "class='preview imageuploaded' target='_blank' ' href='" + obj.imgPath + "'>" + file + " </a> <img src='/resources/btndelete.png' style='display:inline;' onclick=\"DeleteFile('" + obj.imgPath + "','','" + obj.propid + "')\"  class='delete'/>").appendTo('#UploadedFileAfter');

            jQuery('#UploadStatusAfter').html("file has been uploaded sucessfully");
            //jQuery("#UploadButton").hide();
            imagePreview();
        },
        onSubmit: function (file, ext) {
            if (!(ext && /^(txt|doc|docx|xls|xlsx|pdf|jpg)$/i.test(ext))) {
                alert('Invalid File Format.');
                return false;
            }
            jQuery('#UploadStatusAfter').html("Uploading...");
        }
    });
}

function editDocument(status, rowselect) {
    if (rowselect == undefined) {
        if (status != undefined) {
            dg = '#dg' + status;
            row = jQuery(dg).datagrid('getSelected');
        }
        else {
            row = jQuery('#dg').datagrid('getSelected');
        }
    }
    else {
        row = rowselect;
    }
    if (row) {

        if (row.status == 0) {
            jQuery("form#fm :input").attr("disabled", false);
            jQuery("#userDiv :input").attr("disabled", false);
            jQuery("#UploadButton").show();
            jQuery("#userDiv").hide();
            jQuery("#Userapprover2Div").hide();
            jQuery("#approverTQMDiv").hide();
            jQuery("#UserapproverTQMDiv").hide();
        }
        else if (row.status == 10 || row.status == 11) {
            jQuery("form#fm :input").attr("disabled", true);
            jQuery("#userDiv :input").attr("disabled", true);
            jQuery("#UploadButton").hide();
            jQuery("#userDiv").show();
            jQuery("#Userapprover2Div").hide();
            jQuery("#approverTQMDiv").hide();
            jQuery("#UserapproverTQMDiv").hide();
        }
        else if (row.status == 20) {
            jQuery("form#fm :input").attr("disabled", true);
            jQuery("#userDiv :input").attr("disabled", true);
            jQuery("#Userapprover2Div :input").attr("disabled", true);
            jQuery("#UploadButton").hide();
            jQuery("#userDiv").show();
            jQuery("#Userapprover2Div").show();
            jQuery("#approverTQMDiv").hide();
            jQuery("#UserapproverTQMDiv").hide();
            
        }
        else if (row.status == 30 || row.status == 40) {
            jQuery("form#fm :input").attr("disabled", true);
            jQuery("#userDiv :input").attr("disabled", true);
            jQuery("#Userapprover1Div :input").attr("disabled", true);
            jQuery("#Userapprover2Div :input").attr("disabled", true);
            jQuery("#UserapproverTQMDiv :input").attr("disabled", true);

            jQuery("#UploadButton").hide();
            jQuery("#userDiv").show();
            jQuery("#Userapprover2Div").show();
            
        }
        else {
            jQuery("#UploadButton").show();
            jQuery("#userDiv").hide();
            jQuery("#Userapprover2Div").hide();
            
        }

        jQuery('#fm').form('clear');
        jQuery('#UploadedFile').html('');
        jQuery('#UploadedFileAfter').html('');
        jQuery('#dlg').dialog('open').dialog('setTitle', 'แก้ไขแบบฟอร์ม');
        jQuery('#wizard').smartWizard('goToStep', 1);
        jQuery('#wizard').smartWizard('hideMessage');
        //jQuery.uniform.restore(jQuery('select, input:checkbox'));
        jQuery('#fm').form('load', row);
        jQuery.post('/api.ashx?metdhodName=getdocPropbyID', { id: row.id }, function (result) {
            var json = jQuery.parseJSON(result);
            var data = {};
            jQuery.each(json, function (index, d) {

                if (d.dataDate != null || d.dataDate != undefined) {
                    data[d.propertyName] = d.dataDate;
                }
                if (d.dataDecimal != null || d.dataDecimal != undefined) {
                    data[d.propertyName] = d.dataDecimal;
                }
                if (d.dataInt != null || d.dataInt != undefined) {
                    data[d.propertyName] = d.dataInt;
                }
                if (d.dataNtext != null || d.dataNtext != undefined) {
                    data[d.propertyName] = d.dataNtext;
                }
                if (d.dataNvarchar != null || d.dataNvarchar != undefined) {
                    if (d.propertyName == 'approverType') {
                        jQuery('#Userapprover2Div input[type=radio][value=' + d.dataNvarchar + ']').prop('checked', true);
                    }
                    if (d.propertyName == 'approverTQMType') {
                        jQuery('#UserapproverTQMDiv input[type=radio][value=' + d.dataNvarchar + ']').prop('checked', true);
                    }
                    if (d.dataNvarchar.toLowerCase() == 'true') {
                        jQuery('#' + d.propertyName).prop('checked', true);
                    }
                    else if (d.dataNvarchar.toLowerCase() == 'false') {
                        jQuery('#' + d.propertyName).prop('checked', false);
                    }
                    else {
                        if (d.propertyName == 'docImage') {
                            var filename = d.dataNvarchar.substr(d.dataNvarchar.lastIndexOf("/") + 1);
                            if (row.status > 0) {
                                jQuery("<a id='" + d.id + "' " + "class='preview imageuploaded' target='_blank' ' href='" + d.dataNvarchar + "'>" + filename + " </a>").appendTo('#UploadedFile');
                            }
                            else {
                                jQuery("<a id='" + d.id + "' " + "class='preview imageuploaded' target='_blank' ' href='" + d.dataNvarchar + "'>" + filename + " </a> <img src='/resources/btndelete.png' style='display:inline;' onclick=\"DeleteFile('" + d.dataNvarchar + "','" + d.docId + "','" + d.id + "')\"  class='delete'/>").appendTo('#UploadedFile');
                            }
                        }
                        else if (d.propertyName == 'docImageAfter') {
                            var filename = d.dataNvarchar.substr(d.dataNvarchar.lastIndexOf("/") + 1);
                            if (row.status > 0) {
                                jQuery("<a id='" + d.id + "' " + "class='preview imageuploaded' target='_blank' ' href='" + d.dataNvarchar + "'>" + filename + " </a>").appendTo('#UploadedFileAfter');
                            }
                            else {
                                jQuery("<a id='" + d.id + "' " + "class='preview imageuploaded' target='_blank' ' href='" + d.dataNvarchar + "'>" + filename + " </a> <img src='/resources/btndelete.png' style='display:inline;' onclick=\"DeleteFile('" + d.dataNvarchar + "','" + d.docId + "','" + d.id + "')\"  class='delete'/>").appendTo('#UploadedFileAfter');
                            }
                        }
                        else {
                            data[d.propertyName] = d.dataNvarchar;
                        }
                    }
                }

                

            });

            jQuery('#fm').form('load', data);
            jQuery('#userDiv').form('load', data);
            jQuery('#Userapprover2Div').form('load', data);
            //jQuery('select, input:checkbox').uniform();
            imagePreview();

            upload = new AjaxUpload('#UploadButton', {
                action: SaveImage(),
                onComplete: function (file, response) {
                    var obj = jQuery.parseJSON(response);
                    jQuery("<a id='" + obj.propid + "' " + "class='preview imageuploaded' target='_blank' ' href='" + obj.imgPath + "'>" + file + " </a> <img src='/resources/btndelete.png' style='display:inline;' onclick=\"DeleteFile('" + obj.imgPath + "','','" + obj.propid + "')\"  class='delete'/>").appendTo('#UploadedFile');

                    jQuery('#UploadStatus').html("file has been uploaded sucessfully");
                    //jQuery("#UploadButton").hide();
                    imagePreview();
                },
                onSubmit: function (file, ext) {
                    if (!(ext && /^(txt|doc|docx|xls|pdf|jpg)$/i.test(ext))) {
                        alert('Invalid File Format.');
                        return false;
                    }
                    jQuery('#UploadStatus').html("Uploading...");
                }
            });
            uploadAfter = new AjaxUpload('#UploadButtonAfter', {
                action: SaveImage(),
                onComplete: function (file, response) {
                    var obj = jQuery.parseJSON(response);
                    jQuery("<a id='" + obj.propid + "' " + "class='preview imageuploaded' target='_blank' ' href='" + obj.imgPath + "'>" + file + " </a> <img src='/resources/btndelete.png' style='display:inline;' onclick=\"DeleteFile('" + obj.imgPath + "','','" + obj.propid + "')\"  class='delete'/>").appendTo('#UploadedFileAfter');

                    jQuery('#UploadStatusAfter').html("file has been uploaded sucessfully");
                    //jQuery("#UploadButton").hide();
                    imagePreview();
                },
                onSubmit: function (file, ext) {
                    if (!(ext && /^(txt|doc|docx|xls|pdf|jpg)$/i.test(ext))) {
                        alert('Invalid File Format.');
                        return false;
                    }
                    jQuery('#UploadStatusAfter').html("Uploading...");
                }
            });
            getScoreSelect(true);
        });
        urlTag = '/api.ashx?metdhodName=editTag&id=' + row.tagId;
    }
}

function A1ApproveDocument() {
    var row = jQuery('#dgA1').datagrid('getSelected');
    if (row) {
        //jQuery.uniform.restore(jQuery('select, input:checkbox'));
        jQuery('#fmA1').form('clear');
        jQuery('#UploadedFileA1').html('');
        jQuery('#UploadedFileA1After').html('');

        //jQuery('select, input:checkbox').uniform();
        jQuery('#dlgA1').dialog('open').dialog('setTitle', 'อนุมัติแบบฟอร์ม');
        jQuery('#fmA1').form('load', row);
        //jQuery.uniform.restore(jQuery('select, input:checkbox'));
        jQuery.post('/api.ashx?metdhodName=getdocPropbyID', { id: row.id }, function (result) {
            var json = jQuery.parseJSON(result);
            var data = {};
            jQuery.each(json, function (index, d) {

                if (d.dataDate != null || d.dataDate != undefined) {
                    data[d.propertyName] = d.dataDate;
                }
                if (d.dataDecimal != null || d.dataDecimal != undefined) {
                    data[d.propertyName] = d.dataDecimal;
                }
                if (d.dataInt != null || d.dataInt != undefined) {
                    data[d.propertyName] = d.dataInt;
                }
                if (d.dataNtext != null || d.dataNtext != undefined) {
                    data[d.propertyName] = d.dataNtext;
                }
                if (d.dataNvarchar != null || d.dataNvarchar != undefined) {
                    if (d.dataNvarchar.toLowerCase() == 'true') {
                        if (d.propertyName >= 1000) {
                            jQuery('#' + d.propertyName + 'a1').prop('checked', true);
                        }
                        else {
                            jQuery('#approver1Div :input[id=' + d.propertyName + ']').prop('checked', true);
                        }
                        //jQuery('#' + d.propertyName).prop('checked', true);
                    }
                    else if (d.dataNvarchar.toLowerCase() == 'false') {
                        if (d.propertyName >= 1000) {
                            jQuery('#' + d.propertyName + 'a1').prop('checked', false);
                        }
                        else {
                            jQuery('#approver1Div :input[id=' + d.propertyName + ']').prop('checked', false);
                        }

                        //jQuery('#' + d.propertyName).prop('checked', false);

                    }
                    else {
                        if (d.propertyName == 'docImage') {
                            var filename = d.dataNvarchar.substr(d.dataNvarchar.lastIndexOf("/") + 1);
                            jQuery("<a id='" + d.id + "' " + "class='preview imageuploaded' target='_blank' ' href='" + d.dataNvarchar + "'>" + filename + " </a>").appendTo('#UploadedFileA1');
                        }
                        else if (d.propertyName == 'docImageAfter') {
                            var filename = d.dataNvarchar.substr(d.dataNvarchar.lastIndexOf("/") + 1);
                            jQuery("<a id='" + d.id + "' " + "class='preview imageuploaded' target='_blank' ' href='" + d.dataNvarchar + "'>" + filename + " </a>").appendTo('#UploadedFileA1After');
                        }
                        else if (d.propertyName == 'approverType') {
                            jQuery('#approver2Div :input:radio[name=approverType]').filter('[value=' + d.dataNvarchar + ']').prop('checked', true)

                            //jQuery('#approver2Div :input :radio[name=' + d.propertyName + ']').prop('checked', true);
                        }
                        else {
                            data[d.propertyName] = d.dataNvarchar;
                        }
                    }
                }
                
            });

            if (row.approver1 == row.approver2) {
                jQuery('#savedocumentA1Button').hide();
                jQuery('#savedocumentA1UserButton').hide();
                jQuery('input[id="approverTypeA1"][value="1"]').prop('checked', true);
            }
            jQuery('#fmA1').form('load', data);
            jQuery('#approver1Div').form('load', data);
            jQuery('#approver2Div').form('load', data);

            //jQuery('select, input:checkbox').uniform();
            imagePreview();
            getScoreSelect();
        });
        //urlTag = '/api.ashx?metdhodName=editTag&id=' + row.tagId;
    }
}
function removeDocument() {
    var row = jQuery('#dg').datagrid('getSelected');
    if (row) {
        jQuery.messager.confirm('Confirm', 'ต้องการที่จะแบบฟอร์มนี้ ?', function (r) {
            if (r) {
                jQuery.post('/api.ashx?metdhodName=removeDoc', { id: row.id }, function (result) {
                    if (result.success) {
                        jQuery('#dg').datagrid('reload'); // reload the user data
                    } else {
                        jQuery('#dg').datagrid('reload');
                        jQuery.messager.show({	// show error message
                            title: 'Error',
                            msg: result.msg
                        });
                    }
                }, 'json');
            }
        });
    }
}
function getAllInput(section) {
    var datas = [];
    var formSection = "form#fm :input";
    if (section != undefined) {
        formSection = section;
    }
    jQuery(formSection).each(function () {
        var data = {};
        var input = jQuery(this); // This is the jquery object of the input, do what you will
        var name = jQuery(input).attr("id");
        var type = jQuery(input).attr("type");
        if (name != undefined && name != 'undefined') {
            var value;
            data["propertyName"] = name;


            data["dataNtext"] = value;
            if (type == "text") {
                value = jQuery(input).val()
                data["dataNvarchar"] = value;
            }
            else if (type == "checkbox") {
                value = jQuery(input).is(":checked");
                data["dataNvarchar"] = value;
            }
            else if (type == "radio") {
                value = jQuery(input).is(":checked");
                data["dataNvarchar"] = value;
            }
            else if (type == "date") {
                value = jQuery(input).val();
                data["dataDate"] = new Date(value);
            }
            //data["dataInt"] = value;
            //data["dataDecimal"] = value;
            //data["dataDate"] = value;
            datas.push(data);
        }

    });
    jQuery("#UploadedFile .imageuploaded").each(function () {

        var link = jQuery(this);
        var imgSrc = jQuery(this).attr("href");
        var data = { "propertyName": "docImage", "dataNvarchar": imgSrc };
        datas.push(data);
    });
    jQuery("#UploadedFileAfter .imageuploaded").each(function () {

        var link = jQuery(this);
        var imgSrc = jQuery(this).attr("href");
        var data = { "propertyName": "docImageAfter", "dataNvarchar": imgSrc };
        datas.push(data);
    });
    datas.push({ 'propertyname': 'createdDate', 'dataDate': new Date() });


    return datas;
}

function getScoreSelect(isUser) {
    score = 0;
    cash = 0;
    if (isUser) {
        jQuery('#userDiv #tableMeasurement input:radio:checked').each(function (i, i2) {
            score += parseInt(jQuery(i2).val());
            jQuery('#userDiv #totolScore').text(score);
        });
    }
    else {
        jQuery('#approver1Div #tableMeasurement input:radio:checked').each(function (i, i2) {
            score += parseInt(jQuery(i2).val());
            jQuery('#approver1Div #totolScore').text(score);
        });
    }
    
    jQuery('[class^=score]').removeClass('datagrid-row-selected');
    if (score > 3 && score <= 8) {
        jQuery('.score1').addClass('datagrid-row-selected');
        cash = 20;
    }
    else if (score > 8 && score <= 12) {
        jQuery('.score2').addClass('datagrid-row-selected');
        cash = 40;
    }
    else if (score > 12 && score <= 16) {
        jQuery('.score3').addClass('datagrid-row-selected');
        cash = 60;
    }
    else if (score > 16 && score <= 18) {
        jQuery('.score4').addClass('datagrid-row-selected');
        cash = 100;
    }
    else if (score > 18) {
        jQuery('.score5').addClass('datagrid-row-selected');
        cash = 300;
    }

}
function getAllInputApprover1() {
    var datas = [];
    jQuery("#approver1Div :input").each(function () {
        var data = {};
        var input = jQuery(this); // This is the jquery object of the input, do what you will
        var name = jQuery(input).attr("id");
        var type = jQuery(input).attr("type");
        var value;
        data["propertyName"] = name;


        if (type == "text") {
            value = jQuery(input).val()
            data["dataNvarchar"] = value;
        }
        else if (type == "checkbox") {
            value = jQuery(input).is(":checked");
            data["dataNvarchar"] = value;
        }
        else if (type == "radio") {
            if (jQuery(input).is(":checked")) {
                data["propertyName"] = jQuery(input).attr("name");
                value = jQuery(input).val();
                data["dataNvarchar"] = value;
            }
        }
        else if (type == "date") {
            value = jQuery(input).val();
            data["dataDate"] = new Date(value);
        }
        //data["dataInt"] = value;
        //data["dataDecimal"] = value;
        //data["dataDate"] = value;
        if (data["propertyName"] != undefined) {
            datas.push(data);
        }

    });
    return datas;
}

function SaveDoc() {  
    var param = getAllInput();
    param.push({'propertyname': 'approver1', 'dataNvarchar': jQuery('#approver1Section').combobox('getValue') });
    param.push({'propertyname': 'approver2', 'dataNvarchar': jQuery('#approver2Section').combobox('getValue') });
    saveDocument(param);
    jQuery('#approverSelection').dialog('close');
}  

function CancelDoc() {  
        javascript:jQuery('#approverSelection').dialog('close');  
}  
function UserCheckerFunction() {
    if (currentUser != undefined || currentUser != '') {
        jQuery.post('/api.ashx?metdhodName=getemp&empid=' + currentUser, function (result) {
            if (result != null) {
                var d = jQuery.parseJSON(result);
                jQuery('#createdByName').val(d[0].mnameTh + " " + d[0].surnameTh);
                jQuery('#departmentName').val(d[0].sacnameTh);
                //jQuery('#createdBy').val(d[0].mempid);
                //jQuery('#dgA1').datagrid('reload'); // reload the user data
            } else {

            }
            return false;
        });

        return false;
    }
}